<template>
  <div ref="editor" style="text-align:left; position:relative; z-index:1000"></div>
</template>

<script>
import E from "wangeditor";
import { UploadImage } from "@/api/config";
import { syncFileToBlog } from "@/util/util";

export default {
  name: "editor",
  props: ["value"],
  data() {
    return {
      editorContent: ""
    };
  },
  methods: {
    getContent: function() {
      alert(this.editorContent);
    }
  },
  mounted() {
    var editor = new E(this.$refs.editor);
    const self = this;
    editor.customConfig.customUploadImg = async (file, insert) => {
      const vierfyType = ["image/jpeg", "image/png"];
      if (!vierfyType.includes(file[0].type)) {
        self.$message({
          type: "error",
          message: "仅允许上传jpg/png格式的图片"
        });
        return;
      }
      const { blob, blobError } = await syncFileToBlog(file[0]);

      if (blobError) {
        this.$message({
          type: "error",
          message: blobError
        });
        return;
      }

      const { data, error } = await UploadImage(blob, file[0].type);

      if (error) {
        this.$message({
          type: "error",
          message: error.message || String(error)
        });
        return;
      }

      insert(data.bussData.downloadUrl);
    };

    editor.customConfig.menus = [
      "emoticon", // 表情
      "image", // 插入图片
      "head", // 标题
      "bold", // 粗体
      "fontSize", // 字号
      "fontName", // 字体
      "italic", // 斜体
      "underline", // 下划线
      "strikeThrough", // 删除线
      "foreColor", // 文字颜色
      "backColor", // 背景颜色
      "link", // 插入链接
      "justify", // 对齐方式
      "quote", // 引用
      // 'code',  // 插入代码
      "undo", // 撤销
      "redo" // 重复
    ];

    editor.customConfig.onchange = html => {
      this.$emit("input", html);
    };
    editor.create();
    editor.txt.html(this.value);
  }
};
</script>
